package threads;

import android.os.Handler;
import android.os.Looper;
import android.os.Message;
import android.util.Log;


import java.lang.ref.WeakReference;

import customhandler.MyHandler;
import singleton.SingletonClass;

/**
 * Created by admin on 2017/9/21.
 */
public class BaseThread extends Thread {
    public FrameHandler mHandler;

    @Override
    public void run() {
        super.run();
        Looper.prepare();
        mHandler = new FrameHandler(this);
    }

    protected void sendFrameMessage(Message msg) {
        mHandler.sendMessage(msg);
    }

    //处理信息
    public void onHandleFrameMessage(Message msg) {

    }

    protected void sendEmptyFrameMessage(int what) {
        mHandler.sendEmptyMessage(what);
    }
    protected void sendEmptyFrameMessageDelay(int what,long delayMillis) {
        mHandler.sendEmptyMessageDelayed(what,delayMillis);
    }

    /**
     * 处理Activity上消息的Handler
     */
    public static class FrameHandler extends Handler {

        private WeakReference<BaseThread> contexts;

        public FrameHandler(BaseThread baseThread) {
            contexts = new WeakReference<BaseThread>(baseThread);
            SingletonClass.getSingleton(MyHandler.class).registeHandler(this);
        }

        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            if (contexts != null) {
                BaseThread baseThread = contexts.get();
                if (baseThread != null) {
                    try {
                        baseThread.onHandleFrameMessage(msg);
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                }
            }
        }

    }
}
